package com.brave.commonly.utils;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;

import com.brave.commonly.CommonConfig;

import java.lang.reflect.Method;

/**
 * BarUtils
 * <br/>
 * {@link @author} brave tao
 * <br/>
 * {@link @time} 2019/7/24
 * <br/>
 * {@link @description} 状态栏、导航栏帮助
 */
public final class BarUtils {
    // 状态栏
    private static final String STATUS_BAR_TAG = "STATUS_BAR_HELPER_BRAVE";
    // 导航栏
    private static final String NAV_BAR_TAG = "NAV_BAR_HELPER_BRAVE";

    /**
     * 获取（创建）系统 状态栏、导航栏
     *
     * @param isStatusBar 是否为状态栏
     */
    private static View getSystemBar(@NonNull Window window, boolean isStatusBar) {
        ViewGroup decorView = (ViewGroup) window.getDecorView();
        String tag = isStatusBar ? STATUS_BAR_TAG : NAV_BAR_TAG;
        View systemBar = decorView.findViewWithTag(tag);
        if (null == systemBar) {
            systemBar = new View(window.getContext());
            int systemBarHeight = isStatusBar ? ScreenUtils.getStatusBarHeight() : ScreenUtils.getNavBarHeight();
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    FrameLayout.LayoutParams.MATCH_PARENT, systemBarHeight);
            params.gravity = Gravity.TOP;
            systemBar.setLayoutParams(params);
            systemBar.setTag(tag);
            decorView.addView(systemBar);
        }
        return systemBar;
    }

    /**
     * 获取 StatusBar
     */
    private static View getStatusBar(@NonNull Window window) {
        return getSystemBar(window, true);
    }

    /**
     * 获取 NavBar
     */
    private static View getNavBar(@NonNull Window window) {
        return getSystemBar(window, false);
    }

    /**
     * 低度耦合的系统栏目操作方法
     *
     * @param window      视窗
     * @param rootView    根布局
     * @param isStatusBar 需要操作状态栏
     * @param isNavBar    需要操作导航栏
     * @param isFits      状态栏是否占位
     * @param isBlack     状态栏字体是否为黑色
     * @param color       颜色
     * @param defColor    默认颜色
     */
    public static void setBarColor(@NonNull Window window, @NonNull View rootView,
                                   boolean isStatusBar, boolean isNavBar,
                                   boolean isFits, boolean clipToPadding, boolean isBlack,
                                   @ColorInt int color, @ColorInt int defColor) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT || null == rootView) {
            return;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); // draw
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); // status
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION); // navigation
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // 全屏显示，但状态栏不会被隐藏覆盖，状态栏依然可见，Activity 顶端布局部分会被状态遮住
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE; // 防止系统栏隐藏时内容区域大小发生变化
            if (isNavBar) {
                option = option | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION; // 隐藏导航栏
            }
            if (isBlack) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    option = option | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
                } else {
                    color = defColor;
                }
            } else {
                option = option | View.SYSTEM_UI_FLAG_VISIBLE;
            }
            window.getDecorView().setSystemUiVisibility(option);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (isStatusBar) {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            }
            if (isNavBar) {
                window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            }
        }
        if (null != rootView) {
            if (rootView instanceof ViewGroup) {
                ViewGroup viewGroup = (ViewGroup) rootView;
                // 状态栏是否需要占位
                viewGroup.setFitsSystemWindows(isFits);
                // 分割 完成
                viewGroup.setClipToPadding(clipToPadding);
            }
        }
        if (isStatusBar) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.setStatusBarColor(color);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getStatusBar(window).setBackgroundColor(color);
            }
        }
        if (isNavBar) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                window.setNavigationBarColor(color);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                getNavBar(window).setBackgroundColor(color);
            }
        }
    }

    /**
     * 低度耦合的系统栏目操作方法
     *
     * @param activity    活动
     * @param isStatusBar 需要操作状态栏
     * @param isNavBar    需要操作导航栏
     * @param isFits      状态栏是否占位
     * @param isBlack     状态栏字体是否为黑色
     * @param color       颜色
     * @param defColor    默认颜色
     */
    public static void setBarColor(@NonNull Activity activity,
                                   boolean isStatusBar, boolean isNavBar,
                                   boolean isFits, boolean clipToPadding, boolean isBlack,
                                   @ColorInt int color, @ColorInt int defColor) {
        ViewGroup group = activity.findViewById(android.R.id.content);
        if (group.getChildCount() < 1) {
            return;
        }
        setBarColor(activity.getWindow(), group.getChildAt(0),
                isStatusBar, isNavBar, isFits, clipToPadding, isBlack, color, defColor);
    }

    public static void setBarColor(@NonNull Activity activity, @ColorInt int color,
                                   boolean isStatusBar, boolean isNavBar) {
        setBarColor(activity, isStatusBar, isNavBar, true, true, false, color, Color.BLACK);
    }

    public static void setBarColor(@NonNull Activity activity, @ColorInt int color) {
        setBarColor(activity, color, true, false);
    }

    public static void setBarColor(@NonNull Window window, @NonNull View rootView, @ColorInt int color,
                                   boolean isStatusBar, boolean isNavBar) {
        setBarColor(window, rootView, isStatusBar, isNavBar, true, true, false, color, Color.BLACK);
    }

    public static void setBarColor(@NonNull Window window, @NonNull View rootView, @ColorInt int color) {
        setBarColor(window, rootView, color, true, false);
    }

    ///////////////////////////////////////////////////////////////////////////
    // notification
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 设置通知栏是否可见
     *
     * @param isVisible 可见
     */
    public static void setNotificationBarVisibility(final boolean isVisible) {
        String methodName;
        if (isVisible) {
            methodName = (Build.VERSION.SDK_INT <= 16) ? "expand" : "expandNotificationsPanel";
        } else {
            methodName = (Build.VERSION.SDK_INT <= 16) ? "collapse" : "collapsePanels";
        }
        invokePanels(methodName);
    }

    private static void invokePanels(final String methodName) {
        try {
            @SuppressLint("WrongConstant")
            Object service = CommonConfig.getApplication().getSystemService("statusbar");
            @SuppressLint("PrivateApi")
            Class<?> statusBarManager = Class.forName("android.app.StatusBarManager");
            Method expand = statusBarManager.getMethod(methodName);
            expand.invoke(service);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}